package com.software.cool.api.admin.v1.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import com.software.cool.entity.*;
import com.software.cool.mapper.TbRoleMapper;
import com.software.cool.api.admin.v1.service.IAmV1SysUserService;
import com.software.cool.api.admin.v1.vo.AdminLoginUserVO;
import com.software.cool.common.CommonContant;
import com.software.cool.utils.CommonUtils;
import com.software.cool.utils.DateUtils;
import com.software.cool.utils.FileUtils;
import com.software.cool.utils.VideoUtils;
import com.software.cool.service.impl.TbRoleMenuService;
import com.software.cool.service.impl.TbSysUserService;
import lombok.extern.slf4j.Slf4j;
import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AmV1SysUserService implements IAmV1SysUserService {

    @Resource
    private TbSysUserService sysUserService;
    @Resource
    private TbRoleMenuService roleMenuService;
    @Resource
    private TbRoleMapper roleMapper;
    @Resource
    private HttpServletRequest request;

    @Value("${file.basedir}")
    private String basedir;
    @Value("${file.oss}")
    private boolean fileOss;

    @Override
    public AdminLoginUserVO login(String userName, String password,String verifyCode,HttpServletRequest request) {
        AdminLoginUserVO loginUser=new AdminLoginUserVO();
        try{
            String path = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
            if(CommonUtils.isNotBlank(userName) && CommonUtils.isNotBlank(password) && CommonUtils.isNotBlank(verifyCode)){
                if(CommonUtils.isBlank(verifyCode)) {
                    loginUser.setMsg("验证码不能为空");
                    return loginUser;
                }
                HttpSession session = request.getSession();
                String loginDesKey= (String)session.getAttribute(CommonContant.USER_LOGIN_DES_CODE);
                DES des=SecureUtil.des(loginDesKey.getBytes());
                String user=des.decryptStr(userName);
                String pwd=des.decryptStr(password);
                String vcode=des.decryptStr(verifyCode);
                vcode=vcode.toLowerCase();
                String code=(String)session.getAttribute(CommonContant.ADMIN_VERIFY_CODE_SESSION);
                code=code.toLowerCase();
                if(!code.equals(vcode)) {
                    loginUser.setMsg("验证码错误");
                    return loginUser;
                }
//                password=SecureUtil.md5(password);
                TbSysUser sysUser=sysUserService.getLogin(user,pwd);
                if(sysUser!=null){
                    loginUser=new AdminLoginUserVO();
                    List<MenuInfo> menuInfo=roleMenuService.getMenuInfo(sysUser.getRoleId());
                    BeanUtils.copyProperties(sysUser,loginUser);
                    loginUser.setMenuInfo(menuInfo);
                    String token= RandomUtil.randomString(16);
                    loginUser.setToken(token);
                    Date tokenDate= DateUtils.minOffset(new Date(),59);
                    loginUser.setTokenTime(tokenDate.getTime());
                    loginUser.setFileOss(fileOss);
                    loginUser.setBasePath(basePath);
                    session.setAttribute(CommonContant.ADMIN_LOGIN_SESSION, loginUser);
                }else{
                    loginUser.setMsg("账号或密码不正确");
                    return loginUser;
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {
            loginUser.setMsg("服务器连接不上");
            return loginUser;
        }
    }

    @Override
    public InitInfo getInitInfo(String token)throws Exception
    {
        InitInfo initInfo=new InitInfo();
        HomeInfo homeInfo=new HomeInfo("首页","page/welcome");
        initInfo.setHomeInfo(homeInfo);
        LogoInfo logoInfo=new LogoInfo("DIGITCOOL","images/logo.png","");
        initInfo.setLogoInfo(logoInfo);
        List<MenuInfo> menuInfo=new ArrayList<>();
        HttpSession session = request.getSession();
        AdminLoginUserVO loginUser = (AdminLoginUserVO) session.getAttribute(CommonContant.ADMIN_LOGIN_SESSION);
        if(loginUser!=null)
        {
            menuInfo=roleMenuService.getMenuInfo(loginUser.getRoleId());
        }
        initInfo.setMenuInfo(menuInfo);
        return initInfo;
    }

    @Override
    public Long getTokenTime(String token) {
        Long result=0L;
        HttpSession session = request.getSession();
        AdminLoginUserVO loginUser = (AdminLoginUserVO) session.getAttribute(CommonContant.ADMIN_LOGIN_SESSION);
        if(loginUser!=null)
        {
            result=1L;
        }
        return result;
    }


    @Override
    public String[] uploadVideo(MultipartFile file, Map<String, Object> paramsMap, HttpServletRequest request) {
        String videoCover="-";
        String videoPath="-";
        String path = request.getContextPath();
        String ext = FileUtils.getExtend(file.getOriginalFilename());


        String today=DateUtils.format(new Date(),DateUtils.YMD);
        String temp="course/"+today+"/";
        String originPath=basedir+temp;
        FileUtils.existOrmkdir(originPath);
        String fileName=DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_MITIME_STR);
        videoPath=temp+fileName+"."+ext;
        String detailDestination=originPath+fileName+"."+ext;
        File detailFile = new File(detailDestination);
        if (!detailFile.getParentFile().exists()) {
            detailFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(detailFile);
            VideoUtils.getScreenshot(detailDestination);
            videoCover=temp+fileName+".jpg";
        } catch (Exception e) {
            if(detailFile.exists()){
                detailFile.delete();
            }
        }
        return new String[]{videoCover,videoPath};
    }

    @Override
    public String uploadImage(MultipartFile file, Map<String, Object> paramsMap, HttpServletRequest request) {
        String path = request.getContextPath();
        String ext = FileUtils.getExtend(file.getOriginalFilename());
        String today=DateUtils.format(new Date(),DateUtils.YMD);
        String temp="course/"+today+"/";
        String originPath=basedir+temp;
        FileUtils.existOrmkdir(originPath);
        String fileName=DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_MITIME_STR);
        String courseCover=temp+fileName+"."+ext;
        String detailDestination=originPath+fileName+"."+ext;
        File detailFile = new File(detailDestination);
        if (!detailFile.getParentFile().exists()) {
            detailFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(detailFile);
        } catch (Exception e) {
            if(detailFile.exists()){
                detailFile.delete();
            }
        }
        return courseCover;
    }

    @Override
    public String[] uploadApk(MultipartFile file, Map<String, Object> paramsMap, HttpServletRequest request) {

        String appLabel="-";
        String appVersion="-";
        String appCode="0";
        String appPackageName="";
        String path = request.getContextPath();
        String ext = FileUtils.getExtend(file.getOriginalFilename());
        String today=DateUtils.format(new Date(),DateUtils.YMD);
        String temp="apk/"+today+"/";
        String originPath=basedir+temp;
        FileUtils.existOrmkdir(originPath);
        String fileName=DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_MITIME_STR);
        String appPath=temp+fileName+"."+ext;
        String appLogo=temp+fileName+".jpg";

        String detailDestination=originPath+fileName+"."+ext;
        File detailFile = new File(detailDestination);
        if (!detailFile.getParentFile().exists()) {
            detailFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(detailFile);
            //获取app logo
            ApkFile apkFile = new ApkFile(detailDestination);
            ApkMeta apkMeta = apkFile.getApkMeta();
            appVersion=CommonUtils.parseStringData(apkMeta.getVersionName(),"v1.0");
            appLabel=apkMeta.getLabel();
            appCode=apkMeta.getVersionCode()+"";
            appPackageName=apkMeta.getPackageName();
            try {
                byte[] apkByteArray=apkFile.getIconFile().getData();
                FileUtils.getFileFromBytes(apkByteArray,basedir+File.separator+appLogo);
            }catch(Exception e)
            {

            }

        } catch (Exception e) {
            if(detailFile.exists()){
                detailFile.delete();
            }
        }
        return new String[]{appLogo,appPath,appLabel,appVersion,appCode,appPackageName};
    }

    @Override
    public void showImageByServer(String filePath, HttpServletRequest request, HttpServletResponse response) {
        BufferedInputStream bis = null;
        ByteArrayOutputStream out = null;
        String imagePath=basedir+filePath;
        try {
            String exName=FileUtils.getExtend(imagePath).toLowerCase();
            if(exName.equals("jpg") || exName.equals("jpeg") || exName.equals("png")) {
                File file = new File(imagePath);
                FileInputStream iputStream = new FileInputStream(file);
                bis = new BufferedInputStream(iputStream, 1024);
                out = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len = bis.read(bytes)) > 0) {
                    out.write(bytes, 0, len);
                }
                response.setCharacterEncoding("UTF-8");
                if (request.getHeader("User-agent").contains("MSIE")) {
                    response.setHeader("Content-Disposition",
                            String.format("inline;filename=%s", URLEncoder.encode("title", "UTF-8")));
                }
                else {
                    response.setHeader("Content-Disposition",
                            String.format("inline;filename=\"%s\"", new String("title".getBytes("UTF-8"), "ISO8859-1")));
                }
                out.writeTo(response.getOutputStream());
            }else {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().print("<div style=\"font-size: 30px;color:red;margin-top: 120px;text-align: center;\">参数含有非法攻击字符,已禁止继续访问！</div>");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                if(bis!=null) {
                    bis.close();
                }
                if(out!=null)
                {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                //e.printStackTrace();
            }
        }
    }

    @Override
    public void downloadApk(String filePath, HttpServletRequest request, HttpServletResponse response) {
        BufferedInputStream bis = null;
        ByteArrayOutputStream out = null;
        filePath = basedir+filePath;
        try {
            File file = new File(filePath);
            FileInputStream iputStream = new FileInputStream(file);
            bis = new BufferedInputStream(iputStream, 1024);
            out = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
            Date now=new Date();
            response.addHeader("Content-Disposition","attachment;filename=ShipNetApp_"+now.getTime()+".apk");
            response.addHeader("Content-Length", "" + file.length());
            response.setCharacterEncoding("UTF-8");
            out.writeTo(response.getOutputStream());
        } catch (Exception e) {
            //logger.error(e.getMessage(),e);
        } finally {
            try {
                if(bis!=null){
                    bis.close();
                }
                if(out!=null){
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {

            }
        }
    }

    public void downloadExcel(String filePath, HttpServletRequest request, HttpServletResponse response)
    {
        BufferedInputStream bis = null;
        ByteArrayOutputStream out = null;
        filePath = basedir+filePath;
        try {
            File file = new File(filePath);
            FileInputStream iputStream = new FileInputStream(file);
            bis = new BufferedInputStream(iputStream, 1024);
            out = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
            response.addHeader("Content-Disposition","attachment;filename="+DateUtils.format(new Date(),DateUtils.YMD_DASH_WITH_TIME_STR)+".xlsx");
            response.addHeader("Content-Length", "" + file.length());
            response.setCharacterEncoding("UTF-8");
            out.writeTo(response.getOutputStream());
        } catch (Exception e) {
            //logger.error(e.getMessage(),e);
        } finally {
            try {
                if(bis!=null){
                    bis.close();
                }
                if(out!=null){
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {

            }
        }
    }

    public void downloadFile(String filePath, HttpServletRequest request, HttpServletResponse response)
    {
        BufferedInputStream bis = null;
        ByteArrayOutputStream out = null;
        filePath = basedir+filePath;
        try {
            File file = new File(filePath);
            String fileName=FileUtil.getName(filePath);
            String extName=FileUtil.extName(filePath);
            FileInputStream iputStream = new FileInputStream(file);
            bis = new BufferedInputStream(iputStream, 1024);
            out = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
            fileName = URLEncoder.encode(fileName,"UTF-8");
            response.setContentType("application/"+extName+";charset=UTF-8");
            response.addHeader("Content-Disposition","attachment;filename="+fileName);
            response.addHeader("Content-Length", "" + file.length());
            response.setCharacterEncoding("UTF-8");
            out.writeTo(response.getOutputStream());
        } catch (Exception e) {
            //logger.error(e.getMessage(),e);
        } finally {
            try {
                if(bis!=null){
                    bis.close();
                }
                if(out!=null){
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {

            }
        }
    }


}
